package it.getta.vicinometro.utils;

import it.getta.vicinometro.resources.ResBundle;

import java.io.InputStream;
import java.io.OutputStream;

import com.google.android.maps.GeoPoint;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.util.DisplayMetrics;
import android.view.Surface;
import android.view.WindowManager;

public class Utils {
	public static void CopyStream(InputStream is, OutputStream os) {
		final int buffer_size = 1024;
		try {
			byte[] bytes = new byte[buffer_size];
			for (;;) {
				int count = is.read(bytes, 0, buffer_size);
				if (count == -1)
					break;
				os.write(bytes, 0, count);
			}
		} catch (Exception ex) {
		}
	}

	public static int convertDensityPixel(int dip, Context context) {
		return (int) (dip * context.getResources().getDisplayMetrics().density);
	}
	
	public static void hardLong(String message) {
		if (ResBundle.PRINT_DEBUG_MESSAGES) {
			System.out.println("**************");
			System.out.println("************** " + message);
			System.out.println("**************");
		}
	}
	
	public static float pxToDip(Context c, int px) {
		DisplayMetrics metrics = new DisplayMetrics();
		WindowManager wm = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE);
		wm.getDefaultDisplay().getMetrics(metrics);
		float dp = px/(metrics.densityDpi/160f);
	    return dp;
	}
	
	public static GeoPoint locationToGeopoint(Location location) {
		if (location != null) {
			return new GeoPoint((int) (location.getLatitude() * 1e6),
					(int) (location.getLongitude() * 1e6));
		} else {
			return null;
		}
	}
	
	public static Location geopointToLocation(GeoPoint point) {
		Location location = new Location(LocationManager.NETWORK_PROVIDER);
		location.setLatitude(point.getLatitudeE6()/1e6);
		location.setLongitude(point.getLongitudeE6()/1e6);
		return location;
	}
	
	public static int getDisplayWidth(Activity activity) {
		DisplayMetrics metrics = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
		return metrics.widthPixels;
	}
	
	public static int getDisplayHeight(Activity activity) {
		DisplayMetrics metrics = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
		return metrics.heightPixels;
	}
	
	public static boolean isLandscape(Activity activity) {
		int rotation = activity.getWindowManager().getDefaultDisplay().getOrientation();
		return (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180);
	}
	
}